package net.wanho.listener;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import net.wanho.entity.Student;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;


/**
 * 消息接收者/消费者
 */
@Component
public class MsgListener {

    @SneakyThrows
    @RabbitListener(queues = {"queue1"})
    public void readMsg(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
    // public void readMsg(Student stu){
        System.out.println("接收到的消息：" + msg);

        // todo....

        // 如果消息处理成功，则确认消息
        // channel.basicAck(tag, false); // 参数：消息的tag，是否批量处理

        // 如果消息处理失败，则不确认消息
        // channel.basicNack(tag, false, true); // 参数：消息的tag，是否批量处理，是否重复放入队列
        channel.basicNack(tag, false, false); // 参数：消息的tag，是否批量处理，是否重复放入队列

    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("queue2"),
            exchange = @Exchange(value = "exchange2.fanout", type = ExchangeTypes.FANOUT)
    ))
    public void readMsg2(String msg){
        System.out.println("从 queue2 接收到消息：" + msg);
    }

}
